package com.bds.btcdc.adapter.huobi.trade;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.huobi.trade.model.HuobiOrder;
import com.bds.btcdc.adapter.huobi.trade.util.HttpUtilProxy;
import com.bds.btcdc.adapter.huobi.trade.util.HuobiSignature;
import com.bds.btcdc.adapter.zb.service.ZBTradeService;
import com.bds.btcdc.http.HttpUtil;
import com.bds.btcdc.model.MarketData;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.EhcacheUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author: kevin
 * @date: 2018/4/24
 * @description:
 */
public class HuobiClient {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 交易url首部
     */
//    private final String BASE_URL = "https://api.huobipro.com";
    private final String BASE_URL = "https://api.huobi.pro";
    /**
     * 账户余额查询api
     */
    private final String BALANCE_API="/v1/account/accounts/{account-id}/balance";


    /**
     * 获取账户account-id, （与uid不同）
     */
    private final String ACCOUNT_ID_API="/v1/account/accounts";

    /**
     * 下订单
     */
    private final String MAKE_ORDER_API="/v1/order/orders/place";

    /**
     * 查订单详情
     */
    public static final String ORDER_DETAIL = "/v1/order/orders/{order-id}";

    private String access_key;

    private String secert_key;

    private DecimalFormat df = new DecimalFormat(Const.END_WITH_COUNT);

    /**
     * Huobi Api 请求时需要内部id
     */
    private String spot_id;

    private static ConcurrentMap<Long, HuobiClient> userAccess=new ConcurrentHashMap<>();

    private static HuobiClient client;

    public static HuobiClient getInstance(){
        if (client==null){
            client=new HuobiClient();
        }
        return client;
    }

    public static HuobiClient getInstance(Long user_id, String accessKey, String secretKey, String spot_id) {
        HuobiClient client;
        if(!userAccess.containsKey(user_id)) {
            client=new HuobiClient(accessKey,secretKey,spot_id);
            userAccess.put(user_id,client);
            return client;
        }else{
            client=userAccess.get(user_id);
            if (client==null){
                client=new HuobiClient(accessKey,secretKey,spot_id);
                userAccess.put(user_id,client);
                return client;
            }
            return client;
        }
    }
    private HuobiClient() {
    }
    private HuobiClient(String accessKey,String secretKey,String spot_id) {
        this.access_key = accessKey;
        this.secert_key = secretKey;
        this.spot_id=spot_id;
    }

    /**
     * 查询账户余额
     * @return
     */
    public String getBalance() {
        String data = null;
        HttpUtilProxy httpUtil = HttpUtilProxy.getInstance();
        try {
            Map params = new HashMap<String, String>();
            String BALANCE_API_WITH_ID=BALANCE_API.replace("{account-id}",spot_id);
            String add = HuobiSignature.createSignature(access_key, secert_key, "GET", "api.huobi.pro", BALANCE_API_WITH_ID, params);
            String url=BASE_URL + BALANCE_API_WITH_ID+"?"+HuobiSignature.toQueryString(params);
            data = httpUtil.get(url,null,Const.LOCAL);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }

    /**
     * 查询account-id
     * @return
     */
    public String  getAccounts(){
        String data = null;
        HttpUtilProxy httpUtil = HttpUtilProxy.getInstance();
        try {
            Map params = new HashMap<String, String>();
            HuobiSignature.createSignature(access_key, secert_key, "GET", "api.huobi.pro", ACCOUNT_ID_API, params);
            String url=BASE_URL + ACCOUNT_ID_API +"?"+HuobiSignature.toQueryString(params);
            data = httpUtil.get(url,null,true);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }

    /**
     * POST /v1/order/orders/place Pro站下单
     */
    public String makeOrder(HuobiOrder order){
        String data = null;
        HttpUtilProxy httpUtil = HttpUtilProxy.getInstance();
        try {
            Map params = new HashMap<String, String>();
            HuobiSignature.createSignature(access_key, secert_key, "POST", "api.huobi.pro", MAKE_ORDER_API, params);
            String url=BASE_URL + MAKE_ORDER_API +"?"+HuobiSignature.toQueryString(params);
            String json=JSONObject.toJSONString(order).replace("account_id","account-id");
            data = httpUtil.post(url,json,Const.LOCAL);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }

    /**
     * 根据币对获取最新价格
     * @return
     */
    public String getPriceBySymbol(String symbol) {

        HttpUtilProxy httpUtil = HttpUtilProxy.getInstance();
        String param = "?symbol=" + symbol;
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");
        header.put("Content-Type", "application/x-www-form-urlencoded");
        String json = null;
        try {
            json = httpUtil.get(Const.HUOBI.URL + Const.HUOBI.WS_MARKET_INFO + param, header, Const.LOCAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (json == null)
            return null;

        JSONObject object = JSONObject.parseObject(json);
        String status = (String) object.get("status");
        String last=null;
        if (status.equals("ok")) {
            JSONObject tick = object.getJSONObject("tick");
            last = df.format(tick.getBigDecimal("close"));
            //usdt 币对的最新交易价格存到缓存（资产情况统计时 使用）
            EhcacheUtils.getInstance().putCache(Const.HUOBI.EXCHANGE + "#" + symbol, last);
        }
        return last;
    }

    /**
     * 根据orderId，查询订单的详情
     * @param orderId
     * @return
     */
    public String getOrder(String orderId) {
        String data = null;
        HttpUtilProxy httpUtil = HttpUtilProxy.getInstance();
        try {
            Map params = new HashMap<String, String>();
            String _ORDER_DETAIL=ORDER_DETAIL.replace("{order-id}",orderId);
            String add = HuobiSignature.createSignature(access_key, secert_key, "GET", "api.huobi.pro", _ORDER_DETAIL, params);
            String url=BASE_URL + _ORDER_DETAIL+"?"+HuobiSignature.toQueryString(params);
            data = httpUtil.get(url,null,Const.LOCAL);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return data;
    }
}
